package com.easyidea.its.util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;

import javax.imageio.ImageIO;

/**
 * 
 * @author kangning.hu
 * 
 */
public class ImageUtil {
	/**
	 * 
	 * @param srcImageFile
	 * @param config
	 */
	public static void cut(File srcImageFile, FTPConfig config) {
		try {
			Image img;
			ImageFilter cropFilter;
			// 读取源图像
			BufferedImage bi = ImageIO.read(srcImageFile);
			int srcWidth = bi.getWidth(); // 源图宽度
			int srcHeight = bi.getHeight(); // 源图高度
			if (srcWidth >= config.getDestWidth()
					&& srcHeight >= config.getDestHeight()) {
				Image image = bi.getScaledInstance(srcWidth, srcHeight,
						Image.SCALE_DEFAULT);
				// 即: CropImageFilter(int x,int y,int width,int height)
				cropFilter = new CropImageFilter(config.getTopLeftX(), config.getTopLeftY(), config.getDestWidth(), config.getDestHeight());
				img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
				BufferedImage tag = new BufferedImage(config.getDestWidth(),config.getDestHeight(), BufferedImage.TYPE_INT_RGB);
				Graphics g = tag.getGraphics();
				g.drawImage(img, 0, 0, null); // 绘制缩小后的图
				g.dispose();
				// 输出为文件
				ImageIO.write(tag, "JPEG", new File(Config.getString(ItsConstants.FILE_STORE_PATH) + ItsConstants.FILE_SEPERATOR
						+ "cut_"+ srcImageFile.getName()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
